package com.haitaoit.chengquan.module.home.activity;

import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.ScrollView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.haitaoit.chengquan.R;
import com.haitaoit.chengquan.base.BackCall;
import com.haitaoit.chengquan.base.BaseActivity;
import com.haitaoit.chengquan.module.home.activity.forum.ForumDetailActivity;
import com.haitaoit.chengquan.module.home.activity.maintenance.SeachDemandActivity;
import com.haitaoit.chengquan.module.home.activity.maintenance.ServerDetailActivity;
import com.haitaoit.chengquan.module.home.activity.parts.PartsDetailActivity;
import com.haitaoit.chengquan.module.home.adapter.SearchListAdapter;
import com.haitaoit.chengquan.module.home.model.SearchListModel;
import com.haitaoit.chengquan.utils.Constant;
import com.haitaoit.chengquan.utils.DateTimeUtil;
import com.haitaoit.chengquan.utils.GetSign;
import com.haitaoit.chengquan.utils.HttpUtilsSingle;
import com.haitaoit.chengquan.utils.NameValuePairSign;
import com.haitaoit.chengquan.utils.ToastUtils;
import com.haitaoit.chengquan.view.MyListView;
import com.haitaoit.chengquan.view.PullToRefreshBase;
import com.haitaoit.chengquan.view.PullToRefreshScrollView;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.view.annotation.ViewInject;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

public class SearchListActivity extends BaseActivity implements PullToRefreshBase.OnRefreshListener<ScrollView> {
    @ViewInject(R.id.pullrefreshscrollview)
    PullToRefreshScrollView pullrefreshscrollview;

    private ScrollView mScrollView;
    private LinearLayout null_information_layout;
    private MyListView listView;


    private boolean isFrist = true;
    private int page = 1;
    private String search_title;
    private SearchListAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView_V(R.layout.activity_search_list);
        setLeftShow(1, R.mipmap.left);
        setTitle_V("查询结果");
        backLeft_V();
        ViewUtils.inject(this);


        View view = LayoutInflater.from(this).inflate(R.layout.scrollview_listview_layout, null);
        null_information_layout = (LinearLayout) view.findViewById(R.id.null_information_layout);
        listView = (MyListView) view.findViewById(R.id.scrollview_listview);

        pullrefreshscrollview.setPullLoadEnabled(true);
        pullrefreshscrollview.setPullRefreshEnabled(true);
        pullrefreshscrollview.setOnRefreshListener(this);
        pullrefreshscrollview.setLastUpdatedLabel(DateTimeUtil
                .getFormatDateTime(DateTimeUtil.getCurrTimestamp()));
        mScrollView = pullrefreshscrollview.getRefreshableView();
        mScrollView.setFillViewport(true);
        mScrollView.setVerticalScrollBarEnabled(false);
        mScrollView.addView(view);

        adapter = new SearchListAdapter(this);
        adapter.setBackCall(new BackCall() {
            @Override
            public void deal(int which, Object... obj) {
                switch (which) {
                    case R.id.text:
                        Intent intent = new Intent();
                        // type:分类1配件商城2论坛3服务4需求
                        if (adapter.getList().get((Integer) obj[0]).getType().equals("1")) {
                            intent.setClass(SearchListActivity.this, PartsDetailActivity.class);
                        } else if (adapter.getList().get((Integer) obj[0]).getType().equals("2")) {
                            intent.setClass(SearchListActivity.this, ForumDetailActivity.class);
                        } else if (adapter.getList().get((Integer) obj[0]).getType().equals("3")) {
                            intent.setClass(SearchListActivity.this, ServerDetailActivity.class);
                        } else if (adapter.getList().get((Integer) obj[0]).getType().equals("4")) {
                            intent.setClass(SearchListActivity.this, SeachDemandActivity.class);
                        }
                        intent.putExtra("id", adapter.getList().get((Integer) obj[0]).getId());
                        startActivity(intent);
                        break;
                }
                super.deal(which, obj);
            }
        });
        listView.setAdapter(adapter);
        search_title = getIntent().getStringExtra("search_title");
        httpGetsearch_list();
    }

    private void httpGetsearch_list() {
        List<NameValuePairSign> list = new ArrayList<NameValuePairSign>();
        list.add(new NameValuePairSign("name", search_title));
        list.add(new NameValuePairSign("page", page + ""));
        list.add(new NameValuePairSign("pagesize", "20"));
        String sign = GetSign.genPackageSign(list);

        RequestParams params = new RequestParams();
        params.addQueryStringParameter("name", search_title);
        params.addQueryStringParameter("page", page + "");
        params.addQueryStringParameter("pagesize", "20");
        params.addQueryStringParameter("sign", sign);

        HttpUtilsSingle.doGet(this, false, Constant.Getsearch_list, params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> arg0) {
                String result = arg0.result.toString();
                List<SearchListModel> new_list = new ArrayList<SearchListModel>();
                try {
                    JSONObject json = new JSONObject(result);
                    String Errcode = json.getString("ErrCode");
                    String Errmsg = json.getString("ErrMsg");
                    String Response = json.getString("Response");
                    Gson gson = new Gson();
                    switch (Integer.valueOf(Errcode)) {
                        case 1:// 失败
                            ToastUtils.showToast(Errmsg);
                            pullrefreshscrollview.onPullDownRefreshComplete();
                            pullrefreshscrollview.onPullUpRefreshComplete();
                            new_list = new ArrayList<SearchListModel>();
                            break;
                        case 0:// 成功
                            new_list = gson.fromJson(Response,
                                    new TypeToken<List<SearchListModel>>() {
                                    }.getType());
                            break;
                        case 2:// 暂无内容
                            pullrefreshscrollview.onPullDownRefreshComplete();
                            pullrefreshscrollview.onPullUpRefreshComplete();
                            new_list = new ArrayList<SearchListModel>();
                            break;
                    }
                    if (isFrist) {
                        if (isNullDate(new_list)) {
                            adapter.setList(new_list);
                            adapter.notifyDataSetChanged();
                        }
                        pullrefreshscrollview.onPullDownRefreshComplete();
                    } else {
                        List<SearchListModel> allList = adapter.getList();
                        allList.addAll(new_list);
                        adapter.setList(allList);
                        adapter.notifyDataSetChanged();
                        pullrefreshscrollview.onPullUpRefreshComplete();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(HttpException arg0, String arg1) {
                ToastUtils.showToast("获取数据失败,请检查网络");
            }
        });
    }

    /**
     * @tab 判断listview是否有值
     */
    private boolean isNullDate(List<SearchListModel> rewordList) {
        if (rewordList == null || rewordList.size() == 0) {
            null_information_layout.setVisibility(View.VISIBLE);
            listView.setVisibility(View.GONE);
            return false;
        } else {
            null_information_layout.setVisibility(View.GONE);
            listView.setVisibility(View.VISIBLE);
            return true;
        }
    }

    @Override
    public void onPullDownToRefresh(PullToRefreshBase<ScrollView> refreshView) {
        pullrefreshscrollview.setLastUpdatedLabel(DateTimeUtil
                .getFormatDateTime(DateTimeUtil.getCurrTimestamp()));
        isFrist = true;
        page = 1;
        httpGetsearch_list();
    }

    @Override
    public void onPullUpToRefresh(PullToRefreshBase<ScrollView> refreshView) {
        pullrefreshscrollview.setLastUpdatedLabel(DateTimeUtil
                .getFormatDateTime(DateTimeUtil.getCurrTimestamp()));
        isFrist = false;
        page++;
        httpGetsearch_list();
    }
}
